package cn.knightzz.auth;

import cn.knightzz.entity.JsonResult;
import cn.knightzz.entity.SysRole;
import cn.knightzz.entity.SysUser;
import cn.knightzz.service.SysRoleService;
import cn.knightzz.service.SysUserService;
import cn.knightzz.util.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理登录成功操作
 *
 * @author knightzz
 * @date 2021/4/10 13:17
 */
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {

    private final Logger logger = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);


    /**
     * 解决在过滤器中注入对象的问题
     */
    private static SysUserService userService;

    @Resource
    public void setSysUserService(SysUserService userService) {
        MyAuthenticationSuccessHandler.userService = userService;
    }


    // 用于根据角色id查询对应的roleCode
    private static SysRoleService roleService;

    @Resource
    public void setSysRoleService(SysRoleService roleService) {
        MyAuthenticationSuccessHandler.roleService = roleService;
    }

    /**
     * Called when a user has been successfully authenticated.
     *
     * @param request        the request which caused the successful authentication
     * @param response       the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        JsonResult<SysUser> result = new JsonResult<>("200", "登陆成功");
        // 获取用户名 与用户信息
        // username 和 password
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        // 根据用户名获取用户信息
        SysUser user = userService.getUserByUserName(username);
        // 根据角色id获取角色code
        SysRole role = roleService.getRoleById(user.getType().intValue());
        // 生成token
        // 封装数据
        Map<String, String> tokenData = new HashMap<>();
        tokenData.put("username", user.getUsername());
        tokenData.put("roleCode", role.getRoleCode());
        tokenData.put("roleId", role.getId().toString());
        tokenData.put("userId", user.getId().toString());
        // 将封装的数据添加到token中
        String token = JwtUtils.generatorToken(tokenData);
        // 将token插入到数据库中
        user.setToken(token);
        userService.updateUser(user);
        // 在返回结果中填充数据
        result.setData(user);
        // 将结果返回页面
        this.WriteJSON(request, response, result);

    }
}
